package com.gordon.tips.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.gordon.tips.log.Logger;
import com.gordon.tips.log.LoggerImpl;


public class AccessFilter implements Filter {
	
	private static Logger logger = new LoggerImpl(AccessFilter.class);
	

    /**
     * Default constructor. 
     */
    public AccessFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		logger.debug("AccessFilter is working.");
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session=req.getSession();
		//req.setCharacterEncoding("UTF-8");
		
		//locate request url
		String requestUrl = req.getServletPath();
		logger.debug("queryString="+req.getQueryString());
		
		if(req.getQueryString()!=null)requestUrl+="?"+req.getQueryString();
		
		logger.info("request url="+requestUrl);
		if(requestUrl.contains("login")||requestUrl.contains("register"))
			session.setAttribute("currentUrl", "/index.jsp");
		else
			session.setAttribute("currentUrl", requestUrl);
	
		logger.debug("done.");
		chain.doFilter(request, response);
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}
